package com.gict.antifraudback.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gict.antifraudback.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 缓存拦截器
 * @author 18239
 */
@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    @Value("${cache.enable}")
    private boolean enable;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 从缓存中取数据
     * @param request
     * @param response
     * @param handler 执行的方法
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //缓存全局开关
        if (!enable) {
            return true;
        }
        //判断是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //判断是否包含getMapping
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }

        // 判断是否添加Cache注解
        if (!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)) {
            return true;
        }

        //查询缓存
        String redisKey = createRedisKey(request);
        String cacheData = this.redisTemplate.opsForValue().get(redisKey);
        //没有放行
        if (StringUtils.isEmpty(cacheData)) {
            return true;
        }

        // 将data数据进行响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);

        return false;
    }

    /**
     * 生成redis的key
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    public static String createRedisKey(HttpServletRequest request) throws JsonProcessingException {
        String url = request.getRequestURI();
        String s = OBJECT_MAPPER.writeValueAsString(request.getParameterMap());

        String token = request.getHeader("Authorization");

        String data = url + "_" + s + "_" + token;
        return "SERVER_CACHE_DATA" + DigestUtils.md5Hex(data);
    }


}
